#include "legenddelegate.h"
#include <QLabel>
#include <QPainter>


LegendDelegate::LegendDelegate(QObject *parent) :
    QItemDelegate(parent)
{
}
//-----------------------------------------------------------------------------

void LegendDelegate::paint(QPainter *painter,
           const QStyleOptionViewItem &option,
           const QModelIndex &index) const
{
    if (!index.isValid())
        return;

    QString legend = index.data(Qt::EditRole).toString();
    QLabel label(legend);
    label.setFont(option.font);

    QPalette palette = option.palette;
    if (option.state & QStyle::State_Selected) {
        palette.setColor(QPalette::Window, option.palette.color(QPalette::Highlight));
        palette.setColor(QPalette::WindowText, option.palette.color(QPalette::HighlightedText));
    }

    label.setPalette(palette);
    label.adjustSize();
    QPixmap pixmap(label.size());
    label.render(&pixmap);

    QImage img(pixmap.size(), QImage::Format_ARGB32);
    QImage img2 = pixmap.toImage();
    QRgb clr0 = img2.pixel(0, 0);

    for (int n = 0; n < img.width(); ++n) {
        for (int m = 0; m < img.height(); ++m) {
            QRgb clr = img2.pixel(n, m);
            if (clr == clr0) {
                clr = qRgba(255, 255, 255, 0);
            }
            img.setPixel(n, m, clr);
        }
    }

    QImage icon = index.data(Qt::DecorationRole).value<QImage>();
    icon = icon.scaledToHeight(option.rect.height()-4);

    int y = option.rect.y() + (option.rect.height()-img.height())/2;
    int x = option.rect.x() + icon.width() + 5;
    QRect r(x, y, img.width(), img.height());

    drawBackground(painter, option, index);
    painter->drawImage(r, img, img.rect());

    QRect r2(QPoint(option.rect.x(), option.rect.y()+2), icon.size());

    painter->drawImage(r2, icon, icon.rect());

    drawFocus(painter, option, option.rect);
}
//-----------------------------------------------------------------------------
/*
void LegendDelegate::drawBackground(QPainter *painter,
                    const QStyleOptionViewItem &option,
                    const QModelIndex &index) const
{
    if (!index.isValid())
        return;

    painter->save();
    if (option.state & QStyle::State_Selected) {
        qreal y1 = option.rect.y();
        qreal y2 = y1 + option.rect.height();
        QLinearGradient lgrad(QPointF(0.0, y1), QPointF(0.0, y2));
        QColor clr1 = option.palette.color(QPalette::Highlight);
        QColor clr0 = clr1;
        clr0.setAlpha(150);
        clr1.setAlpha(255);
        lgrad.setColorAt(0, clr0);
        lgrad.setColorAt(1.0, clr1);
        painter->setBrush(QBrush(lgrad));
        painter->setPen(Qt::NoPen);
        painter->setRenderHint(QPainter::Antialiasing, true);
        painter->drawRoundRect(option.rect, 5, 5);
        painter->setRenderHint(QPainter::Antialiasing, false);
    }
    painter->restore();
}
*/
//-----------------------------------------------------------------------------

